
#include <BStyle>
#include <BFont>
#include <BWidget>
#include "member_BTabWidget.h"
#include "member_BAction.h"

using namespace BWE;

#define a_member(action)	((member_BAction*)action->_ptr)

member_BTabWidget::member_BTabWidget(BTabWidget* tabWidget)
{
	boss = tabWidget;
	space = 5;
	tabSize.set(32, 22);
	iconSize.set(22, 22);
	begin = 0;
	hoverIndex = 0;
	hoverClose = false;
	tabClosable = false;
	dirty = true;
}
member_BTabWidget::~member_BTabWidget()
{

}

void member_BTabWidget::procTitleChanged(BObject* object, const BValue& value)
{
	BWidget* widget = dynamic_cast<BWidget*>(object);
	if (items.contain(widget))
	{
		boss->fresh();
	}
}

void member_BTabWidget::freshRects()
{
	const BStyle* style = boss->realStyle();
	const BFont* font = boss->font();

	int top = iconSize.width() + space + space;
	if (font)
		top = font->height() + space + space;

	int border = boss->border();
	BPerchs perchs = boss->perchs();
	if (perchs.top() < top)
	{
		perchs.top() = top;
		boss->setPerchs(perchs);
	}
	BMargins margins = boss->margins();

	int cx = border + margins.left() + space;
	int y = border + space;
	int h = bMax(tabSize.height(), perchs.top()) - space;

	int x = cx;
	for(auto& item : items)
	{
		item.textSize.set(0, 0);

		if (style)
			style->trans(item.widget->title(), item.t_title);
		else
			item.t_title.clear();

		if (font)
		{
			if (item.t_title.size())
				item.textSize = font->textSize(item.t_title);
			else
				item.textSize = font->textSize(item.widget->title());
		}

		item.iconRect.set(x, y, 0, 0);
		if (item.icon)
		{
			item.iconRect.set(x, y, h, h);
		}
		item.textRect.set(item.iconRect.right(), y, item.textSize.width(), h);
		item.closeRect.set(item.textRect.right(), y, 0, 0);
		if (tabClosable)
		{
			item.closeRect.setSize(h, h);
			item.rect += BSize(h, 0);
		}
		item.rect.set(x, y, item.closeRect.right() - x, h);
		x += item.rect.width() + space;
	}
}
void member_BTabWidget::reviseTab()
{

}

int member_BTabWidget::indexOf(BWidget* widget)
{
	for(BList<TabItem>::iterator it = items.begin(); it != items.end(); it++)
	{
		TabItem& item = *it;
		if(item.widget == widget)
		{
			return it.index();
		}
	}
	return -1;
}
BRect member_BTabWidget::rectOf(BWidget* widget)
{
	for(BList<TabItem>::iterator it = items.begin(); it != items.end(); it++)
	{
		TabItem& item = *it;
		if(item.widget == widget)
		{
			return it->rect;
		}
	}
	return BRect();
}
